//
// Created by admin on 2024/8/5.
//
#include "hal-delay.h"
#include "port_stm32.h"


#include "ArduinoAPI/Platform/platform_config.h"

#ifndef SYSTICK_TICK_FREQ
#define SYSTICK_TICK_FREQ		1000 // Hz
#endif

#define SYSTICK_TICK_INTERVAL   (1000 / SYSTICK_TICK_FREQ)
#define SYSTICK_LOAD_VALUE      (F_CPU / SYSTICK_TICK_FREQ)
#define SYSTICK_MILLIS          (SystemTickCount * SYSTICK_TICK_INTERVAL)

static volatile uint32_t SystemTickCount = 0;

uint32_t millis(void) {
    return HAL_GetTick();
}

uint32_t micros(void) {
    uint32_t ms, cycle_cnt;

    do {
        ms        = millis();
        cycle_cnt = SysTick->VAL;
    } while (ms != millis());

    return (ms * 1000) + ((cycle_cnt / SYSTICK_LOAD_VALUE) * 1000);
}

void delay_ms(uint32_t ms) {
    HAL_Delay(ms);
}

void delay_us(uint32_t us) {
    uint32_t start = micros();

    while (micros() - start < us) {
        asm volatile ("nop");
    }
}

void delay(uint32_t ms){
    delay_ms(ms);
}